package com.huangwei.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.huangwei.model.Banner;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@Component
@Aspect
public class SetUrl {
    @Around("execution(public * com.huangwei.dao.*.query*(..))")
    public Object setUrl(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String contextPath = request.getScheme() + "://"
                + request.getServerName()
                + ":" + request.getServerPort()
                + request.getContextPath() + "/"
                + "images/";
        List<Object> objectList = (List<Object>) joinPoint.proceed();
        List<Object> newObjList = new LinkedList<>();
        objectList.stream()
                        .forEach(object -> {
                            String json = JSON.toJSONString(object);
                            String newJson = json.replaceAll("(\\w*/\\w*\\.\\w*)",
                                    contextPath + "$1");
                            Object obj = JSONObject.parseObject(newJson, object.getClass());
                            newObjList.add(obj);
                        });
        return newObjList;
    }
}
